//$(document).ready (function () {	// When the DOM is ready
	//$('head').append ('<link rel="stylesheet" href="css/style.css"/>');		// Add depending on user settings?
	
//});

/**
 * All functionality for the pages (and elements) is held in this class
 */

function Page () {
	this.current = 1;			// Currently selected page (firstpage of application)
	this.css = 1;
}

var page = new Page();	// Create an object of the Folders class

/**
 * Initialization function for the Page class
 */
Page.prototype.init = function () {
	this.getPageCss(1);
	// Pageid 1 will ALWAYS be the main/first page (cannot be deleted?)
    this.showMainMenu(1);   // Build the navigation(menu)
	this.getUserOptions(1);
    this.fetchElements(1);  // Get the elements belonging to the page
	 $('.carousel').carousel();
}

Page.prototype.getPage = function (id) {
    this.current = id;
	this.getPageCss(id);
    this.showMainMenu(id);   // Build the navigation(menu)
	this.getUserOptions(id);
    this.fetchElements(id);  // Get the elements belonging to the page
	$('li[id="page_'+id+'"]').toggleClass('open'); // Open dropdown
	 $('.carousel').carousel();
}

/*
 * Gets (and appends) the current page's CSS
 * 
 * @param The id of the page to get the CSS for
 */
Page.prototype.getPageCss = function(id) {
	$.ajax({
    	url: 'includes/functions/getPageCss.php',
		type: 'post',
		data: {id: id},
    	success: function (data) {  // When data is returned
			page.css = data.themeId;
			$('head link[rel="stylesheet"]').remove();
			// Bootstrap CSS
			$('head').append('<link href="includes/bootstrap/css/'+data.themeFile+'" rel="stylesheet">');
			// Custom CSS
			$('head').append('<link href="css/mainstyle.css" rel="stylesheet">');
		}    
    });
}

/**
 * Builds the mainmenu of the site
 *
 * @param int id The current pageId
 */
Page.prototype.showMainMenu = function (id) {
	$.ajax({
    	url: 'includes/functions/getMenuPages.php',
    	success: function (data) {  // When data is returned
            $("#mainMenu").empty();
    		for (var i=0; i<data.length; i++) {     // Loop through all returned data and append the pages without parents to the navigation
    			if(data[i].parent < 0) {			// If the page does not have a parent
					if(id == data[i].pageId) {      // Add the "active"-class if this is the current page:
						$('#mainMenu').append('<li class="active" id="page_'+data[i].pageId+'"><a href="javascript:page.getPage('+data[i].pageId+');">'+data[i].pageName+'</a></li>');
					}
					else {
						$('#mainMenu').append('<li id="page_'+data[i].pageId+'"><a href="javascript:page.getPage('+data[i].pageId+');">'+data[i].pageName+'</a></li>');
					}
				}
			}
			
			for (var i=0; i<data.length; i++) {     // Loop through all returned data and append the rest to their parents
    			if(data[i].parent > 0) {			// If the page has a parent
					if(!$('#page_'+data[i].parent).hasClass("dropdown")) {					// Check if already a dropdown
						$('#page_'+data[i].parent).addClass("dropdown");					// Add the dropdown-class to the parent
						$('#page_'+data[i].parent+' a').addClass("dropdown-toggle disabled");		// Add the dropdown-toggle-class to the link
						$('#page_'+data[i].parent+' a').attr("data-toggle", "dropdown");			// Add the extra attributes to link:
						$('#page_'+data[i].parent+' a').attr("role", "button");
						$('#page_'+data[i].parent+' a').attr("data-target", "#");
						$('#page_'+data[i].parent+' a').attr("onclick", "javascript:page.getPage('"+data[i].parent+"');"); // AAAARGH
						$('#page_'+data[i].parent+' a').append(' <span class="caret"></span>');
						$('#page_'+data[i].parent).append('<ul class="dropdown-menu"></ul>');
					}

					if(id == data[i].pageId) {      // Add the "active"-class if this is the current page:
						$('#page_'+data[i].parent+' ul').append('<li class="active" id="page_'+data[i].pageId+'"><a href="javascript:page.getPage('+data[i].pageId+');">'+data[i].pageName+'</a></li>');
						$('#page_'+data[i].parent).addClass("active");
					}
					else {
						$('#page_'+data[i].parent+' ul').append('<li id="page_'+data[i].pageId+'"><a href="javascript:page.getPage('+data[i].pageId+');">'+data[i].pageName+'</a></li>')
					}
				}
    		}
    	}
    });
}

/**
 * Gets and displays the elements belonging to the current page
 *
 * @param int id The current pageId
 */
Page.prototype.fetchElements = function (id) {
    $.ajax ({
		url: 'includes/functions/fetchElements.php',// Use this script to get a list of elements to display
		data: {'id': id},
		async: false,
		type: 'post',
		success: function (data) {		            // When data is returned
            $(".main").empty();
            $('.main').append('<ul id="element_list" class="column">');
			for (var i=0; i<data.length; i++) {		// Loop through all returned data and append each element to the page
				$('#element_list').append ('<li id="'+data[i].id+'"><h2 id="'+data[i].id+'" class="element-title">'+data[i].title+' </h2>');
				if(isUserLoggedIn() == "true" && page.ownsElement(data[i].id) == "true") {
					if(data[i].isCarousel == 1) {
						$('h2[id="'+data[i].id+'"]').append('<a class="btn btn-sm btn-primary" href="javascript:page.editCarousel('+data[i].id+');" title="Rediger element"><span class="glyphicon glyphicon-edit"></span></a> ');
					}
					else {
						$('h2[id="'+data[i].id+'"]').append('<a class="btn btn-sm btn-primary" href="javascript:page.editElement('+data[i].id+');" title="Rediger element"><span class="glyphicon glyphicon-edit"></span></a> ');
					}
					$('h2[id="'+data[i].id+'"]').append('<a class="btn btn-sm btn-danger" href="javascript:page.deleteElement('+data[i].id+');" title="Slett element"><span class="glyphicon glyphicon-remove"></span></a>');
				}
				if(data[i].showDate == "1") {
					if(data[i].edited) {
						$('li[id="'+data[i].id+'"]').append ('<p class="element-meta">Redigert: '+data[i].edited+'</p>');
					}
					else {
						$('li[id="'+data[i].id+'"]').append ('<p class="element-meta">Publisert: '+data[i].created+'</p>');
					}
				}
				$('li[id="'+data[i].id+'"]').append (data[i].content+'</li>');				   
			}
			$('.main').append('</ul>');
			$( 'ul.column' ).sortable({revert: true});
			$( 'ul.column' ).sortable('disable');
		}
	});
}

/**
 * Checks if the logged in user owns an element
 * 
 * @param int id The id of the element to check
 * @return string "true" or "false".
 */
Page.prototype.ownsElement = function(id) {
	var res = "";
	$.ajax({
		url: "includes/functions/ownsElement.php",
		type: 'post',
		data: { id: id },
		async: false,					// To be able to return info
		success: function (data){
			res = data.respond;
		}
	});
	return res;
}

/**
 * Checks if the logged in user owns a page
 * 
 * @param int id The id of the page to check
 * @return string "true" or "false".
 */
Page.prototype.ownsPage = function() {
	var res = "";
	$.ajax({
		url: "includes/functions/ownsPage.php",
		type: 'post',
		data: { id: this.current },
		async: false,					// To be able to return info
		success: function (data){
			res = data.respond;
		}
	});
	return res;
}

/**
 * Displays user options depending on wheter user owns page or not
 * And the option to delete page only if the page is not id=1
 *
 * @param int id The current pageId
 */
Page.prototype.getUserOptions = function(id) {
	var test = this.ownsPage();
	if(isUserLoggedIn() == "true"){ //User is signed in
		if (page.ownsPage() == "true" && id == 1) {
			$('#userOptions').load("includes/sitePages/userOptionsOwnerFirst.html");
		}
		else if(page.ownsPage() == "true") {
			$('#userOptions').load("includes/sitePages/userOptionsOwner.html");
		}
		else {
			$('#userOptions').load("includes/sitePages/userOptions.html")
		}
	}else {
		$("#userOptions").load("includes/sitePages/sidebarRegUserModule.html");
	}
}
	

/**
 * Gets the parent of a page
 * 
 * @param int id The id of the page to find parent of
 * @return int Id of the parent
 */
Page.prototype.hasParent = function(id) {
	var res = "";
	$.ajax({
		url: "includes/functions/hasParent.php",
		type: 'post',
		data: { id: id },
		async: false,					// To be able to return info
		success: function (data){
			res = data.respond;
		}
	});
	return res;
}

/**
 * Initialises creation of a new page
 *
 */
Page.prototype.newPage = function() {
	$('#newPageContent').load('newPage.html');
	var currentParent = page.hasParent(this.current);
	$.ajax ({
		url: 'includes/functions/getMenuPages.php',  // Use this script to get the exsisting pages
		type: 'post',
		data: { onlyTopLevel: true },
		success: function (data) {		            // When data is returned
			$('select[id="parent"]').append ('<option value="-1">-- Ikke en underside --</option>');
			for (var i=0; i<data.length; i++) {		// Loop through all returned data and append each element to the page
				if(currentParent != '-1' && currentParent == data[i].pageId) {
					$('select[id="parent"]').append ('<option value="'+data[i].pageId+'" selected>'+data[i].pageName+'</option>');
				}
				else if(currentParent == '-1' && data[i].pageId == page.current) { // Set the current page as selected
					$('select[id="parent"]').append ('<option value="'+data[i].pageId+'" selected>'+data[i].pageName+'</option>');
				}
				else {
					$('select[id="parent"]').append ('<option value="'+data[i].pageId+'">'+data[i].pageName+'</option>');
				}
			}
			// Get and append the themes:
			$.ajax ({
				url: 'includes/functions/getThemes.php',  // Use this script to get list of themes
				success: function (data) {		            // When data is returned
					for (var i=0; i<data.length; i++) {		// Loop through all returned data and append each element to the page
						if(data[i].themeId == page.css) {
							$('select[id="css"]').append ('<option value="'+data[i].themeId+'" selected>'+data[i].themeName+'</option>');
						}
						else {
							$('select[id="css"]').append ('<option value="'+data[i].themeId+'">'+data[i].themeName+'</option>');
						}
					}
				}	
			});
			$('#newPage').modal('show');  	// Show the New Element dialog
		}
	});
}

/**
 * Initialises editing of a new page
 *
 */
Page.prototype.editPage = function() {
	$('#newPageContent').load('newPage.html');	// Get the form-html
	$.ajax ({
		url: 'includes/functions/getPage.php',  // Use this script to get the exsisting page
		type: 'post',
		data: { id: this.current },
		success: function (data) {		            // When data is returned
			if(data.message) {						// If something is wrong
				alert (data.message);
			}
			else {									// All is ok, fill in page data in form:
				$('h4[class="modal-title"]').text('Rediger side');
				$('#newPageForm input[type="text"]').val(data.pageName);  
				if(data.private == 1) {
					$('#newPageForm input[type="checkbox"]').prop('checked', true);
				}
				$('#newPageForm input[type="button"]').attr("onClick", "javascript: page.storeEditedPage(this.form);");
				$('#newPageForm').append('<input type="hidden" name="pageid" value="'+data.pageId+'">');
				$.ajax ({
					url: 'includes/functions/getMenuPages.php',  // Use this script to get the exsisting pages
					type: 'post',
					data: { onlyTopLevel: true },
					success: function (tmp) {		            // When data is returned
						$('select[id="parent"]').append ('<option value="-1">-- Ikke en underside --</option>');
						$.ajax ({								// Check if is a parent already:
							url: 'includes/functions/isParent.php',
							type: 'post',
							data: { id: data.pageId },
							success: function (res) {
								if(res.val == true) {			// Is a parent and cant be child-page:
									// Disable and give message to user
									$('fieldset[id="parentSelect"]').attr("disabled", true)
									$('fieldset[id="parentSelect"] div').append('<div class="alert alert-info">Denne siden har allerede undersider, og kan derfor ikke bli en ny underside.</div>');
								}
								else {
									for (var i=0; i<tmp.length; i++) {		// Loop through all returned data and append each element to the page
										if(tmp[i].pageId == data.parent) { // Set the parent as selected
											$('select[id="parent"]').append ('<option value="'+tmp[i].pageId+'" selected>'+tmp[i].pageName+'</option>');
									}
										else {
											$('select[id="parent"]').append ('<option value="'+tmp[i].pageId+'">'+tmp[i].pageName+'</option>');
										}
									}
								}
							}
						});
					}
						
				});
				$.ajax ({
					url: 'includes/functions/getThemes.php',  // Use this script to get list of themes
					success: function (data) {		            // When data is returned
						for (var i=0; i<data.length; i++) {		// Loop through all returned data and append each element to the page
							if(data[i].themeId == page.css) {
								$('select[id="css"]').append ('<option value="'+data[i].themeId+'" selected>'+data[i].themeName+'</option>');
							}
							else {
								$('select[id="css"]').append ('<option value="'+data[i].themeId+'">'+data[i].themeName+'</option>');
							}
						}
					}	
				});
				$('#newPage').modal('show');  	// Show the dialog
			}
		}
	});
}

/**
 * Creates a new page in the database
 *
 * @param form Content of HTML-form (newPage.html)
 */
Page.prototype.storeNewPage = function(form) {
	if(form.privat.checked) {
		var privat = 1;
	}
	else {
		var privat = 0;
	}
	$.ajax ({
		url: 'includes/functions/newPage.php',      // Use this script to store new Page
		type: 'post',
		data: { name: form.name.value, parent: form.parent.value, css: form.css.value, privat: privat },
		success: function (data) {		            // When data is returned
			if (data.ok) {
				alert (data.message);
				page.getPage(data.id);			// "Load" the new page
				$('#newPage').modal('hide');  	// Hide the New Element dialog
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();
				$('#newPageContent').empty();  	// Empty the modal
			} else
				alert (data.message);
			}
	});
}

/**
 * Uptades a page in the database
 *
 * @param form Content of HTML-form (newPage.html, edit-version)
 */
Page.prototype.storeEditedPage = function(form) {
	if(form.privat.checked) {
		var privat = 1;
	}
	else {
		var privat = 0;
	}
	$.ajax ({
		url: 'includes/functions/editPage.php',      // Use this script to store new Page
		type: 'post',
		data: { id: form.pageid.value, name: form.name.value, parent: form.parent.value, css: form.css.value, privat: privat },
		success: function (data) {		            // When data is returned
			if (data.error) {
				alert (data.error);
			} else
				alert (data.message);
				page.getPage(data.id);			// "Load" the new page
				$('#newPage').modal('hide');  	// Hide the dialog
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();
				$('#newPageContent').empty();  	// Empty the modal
			}
	});
}

/**
 * Initilises the creation of a new element
 *
 */
Page.prototype.newElement = function () {
  $.ajax({
    url: 'newElement.html',
    success: function (data) {
      $('#newElementContent').html (data);
      $('#newElementText').tinymce({
		language : 'nb',
		// Location of TinyMCE script
		script_url : 'includes/tinymce/jscripts/tiny_mce/tiny_mce_gzip.php',
		// General options
		theme : "advanced",
		skin: "bootstrap",				// Nicer skin to match bootstrap better
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,advlist,spellchecker",

		// Theme options
		theme_advanced_buttons1 : "spellchecker,iespell,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,removeformat,help,code,|,visualchars,nonbreaking,visualaid,|,insertdate,inserttime",
		theme_advanced_buttons3 : "tablecontrols,|,sub,sup,|,charmap,emotions,media,advhr,|,print,|,fullscreen,|,cite,abbr,acronym,del,ins",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
 
		spellchecker_languages : "Norwegian=no,+English=en",
		file_browser_callback : 'fileBrowser',
		
		height : 400,
		width : 859,
		relative_urls: true,
  		extended_valid_elements : "iframe[src|frameborder|style|scrolling|class|width|height|name|align]"
	  });
	}
  });
  $('#newElement').modal('show');  // Display the New Element dialog
}

/**
 * Initilises editing of an element
 *
 */
Page.prototype.editElement = function (id) {
  $('#newElementContent').load('newElement.html');	// Get the form-html
  var currentPage = this.current;
	$.ajax ({
		url: 'includes/functions/getElement.php',  // Use this script to get the exsisting element
		type: 'post',
		data: { id: id },
		success: function (data) {		            // When data is returned
			if(data.message) {						// If something is wrong
				alert (data.message);
			}
			else {									// All is ok, fill in page data in form:
				$('h4[class="modal-title"]').text('Rediger element');
				$('#newElementForm input[id="title"]').val(data.elementTitle);  
				$('#newElementText').tinymce({
					language : 'nb',
					// Location of TinyMCE script
					script_url : 'includes/tinymce/jscripts/tiny_mce/tiny_mce_gzip.php',
					// General options
					theme : "advanced",
					skin: "bootstrap",				// Nicer skin to match bootstrap better
					plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,advlist,spellchecker",

					// Theme options
					theme_advanced_buttons1 : "spellchecker,iespell,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
					theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,removeformat,help,code,|,visualchars,nonbreaking,visualaid,|,insertdate,inserttime",
					theme_advanced_buttons3 : "tablecontrols,|,sub,sup,|,charmap,emotions,media,advhr,|,print,|,fullscreen,|,cite,abbr,acronym,del,ins",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : true,
 
					spellchecker_languages : "Norwegian=no,+English=en",
					file_browser_callback : 'fileBrowser',
		
					height : 400,
					width : 859,
					relative_urls: true,
					extended_valid_elements : "iframe[src|frameborder|style|scrolling|class|width|height|name|align]",
					init_instance_callback : function() { tinyMCE.activeEditor.setContent(data.elementText);}  // Fill inn tinymce with exsisting content
				});
				// Insert input for moving of the element to another page:
				$('<label for="page">Flytt til annen side:</label><div class="form-group"><select id="page" name="page" class="form-control"></select></div>').insertBefore($('div[class="checkbox"]'));
				// Get and append the options of other pages:
				$.ajax ({
					url: 'includes/functions/getMenuPages.php',  // Use this script to get the exsisting pages
					type: 'post',
					data: { forUser: true },
					success: function (data) {		            // When data is returned
						$('select[id="page"]').append ('<option value="0" selected>-- Ikke flytt siden --</option>');
						for (var i=0; i<data.length; i++) {		// Loop through all returned data and append each element to the page
							if(data[i].pageId != currentPage) {
								$('select[id="page"]').append ('<option value="'+data[i].pageId+'">'+data[i].pageName+'</option>');
							}
						}
					}
				});
				if(data.elementIndex < 999) {
					$('#newElementForm input[type="number"]').val(data.elementIndex);
				}
				if(data.showDate == 0) {
					$('#newElementForm input[type="checkbox"]').prop('checked', true);
				}
				$('#newElementForm input[type="button"]').attr("onClick", "javascript:storeEditedElement(this.form);");
				$('#newElementForm').append('<input type="hidden" name="elementid" value="'+data.elementId+'">');
				
				$('#newElement').modal('show');  	// Show the dialog
			}
		}	
	});
}

/**
 * Stores the new element
 *
 * @param form Content of HTML-form (newElement.html)
 */
Page.prototype.storeNewElement = function(form) {
  if(form.showDate.checked) {
		var showDate = 0;
	}
	else {
		var showDate = 1;
	}
  $.ajax({
	url: 'includes/functions/storeNewElement.php',
	type: 'post',
	data: {title: form.title.value, content: $('#newElementText').html(), pageId: this.current, index: form.index.value, showDate: showDate},
	success: function (data) {
	  if (data.ok) {
	    alert (data.message);
		page.getPage(page.current);					// "Reload" the page (this.current fungerer ikke)
		$('#newElement').modal('hide');  	// Hide the New Element dialog
		$('body').removeClass('modal-open');
		$('.modal-backdrop').remove();
		$('#newElementContent').empty();  	// Empty the modal
	  } else
	    alert (data.message);
	}
  });
}

/**
 * Stores an edited element
 * For some reason this refuses to work as a class function...
 *
 * @param form Content of HTML-form (newElement.html, edit version)
 */
function storeEditedElement(form) {
	if(form.showDate.checked) {
		var showDate = 0;
	}
	else {
		var showDate = 1;
	}
	$.ajax({
		url: 'includes/functions/storeEditedElement.php',
		type: 'post',
		data: {id: form.elementid.value, title: form.title.value, content: $('#newElementText').html(), index: form.index.value, page: form.page.value, showDate: showDate},
		success: function (data) {
			if (data.ok) {
				alert (data.message);
				page.getPage(data.id);			// "Reload" the page (this.current fungerer ikke)
				$('#newElement').modal('hide');  	// Hide the New Element dialog
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();
				$('#newElementContent').empty();  	// Empty the modal
			}
			else {
				alert (data.message);
			}
		}
	});
}

/**
 * Initialises Drag and drop sorting of a page
 *
 */
Page.prototype.moveElement = function() {
	$( 'ul.column' ).sortable('enable');					// Enable sorting
	$("#ChangeElementLocation").removeClass("btn-primary");	// Change the button(s:
	$("#ChangeElementLocation").addClass("btn-success");
	$("#ChangeElementLocation").text("Lagre verdi");
	$("#CancelElementLocation").attr("style", "display: block;");	// Show the cancel button
	$("#ChangeElementLocation").attr("href", "javascript:page.saveSorting();");
	$("#CancelElementLocation").attr("href", "javascript:page.cancelDrag();");
}

 /**
  * Saves the sorting done by the Drag and drop sorting
  *
  */
Page.prototype.saveSorting = function() {
	var ok = true;
	var message= "";
	var currentPage = this.current;
	$('#element_list>li').each(function(i, li) {	// For each element on the page:
		var id = $(li).attr('id');					// Get the id of the element
		var index = i+1;
		$.ajax({
			url: 'includes/functions/setIndex.php',		// Update it's index in the database:
			async: false,
			type: 'post',
			data: { id: id, index: index, siteId: currentPage },
			success: function (data) {
				if (data.fail) {
					alert(data.fail);
					ok = false;
				}
			},
			error: function () {
				ok = false;
				message = "Det skjedde desverre en feil under oppdatering av siden.";
			}
		});
		if(ok == false) {						// If something is wrong:
			return false;						// End the each-loop
		}
	});
	if(ok == true) {							// Give message to user:
		alert('Siden har blitt oppdatert med sorteringen');
	}
	if(message != "") {
		alert(message);
	}
	if (ok == false) {							// Cancel the sorting (revert) if something is wrong:
		$( 'ul.column').sortable('cancel');
	}
	$( 'ul.column').sortable('disable');		// Disable the sorting
	this.getUserOptions(this.current);			// Load the sidebar options again (to reset buttons)
}

/*
 * Cancels the Drag and drop sorting
 *
 */
Page.prototype.cancelDrag = function(){
	 $( 'ul.column').sortable('disable');			// Disable and cancel (revert) the sorting:
	 $( 'ul.column').sortable('cancel');
	 this.getUserOptions(this.current);				// Load the sidebar options again (to reset buttons)
}

/**
 * Deletes the current page
 *
 */
Page.prototype.deletePage = function() {
	// Ask user if this is really the intended action:
	var r=confirm("Er du sikker på at du vil slette denne siden og alle dens elementer?");
	// If "yes", delete the page:
	if (r==true) {
		$.ajax({
			url: 'includes/functions/deletePage.php',
			type: 'post',
			data: { id: this.current },
			success: function (data) {
				alert(data.message);
				if(data.ok) {
					page.init();
				}
			}
		});
	}
	else {	// If not cancel the operation:
		return;
	}
}

/**
 * Deletes an element
 *
 * @param int id The is of the element to delete
 */
Page.prototype.deleteElement = function(id) {
	var currentPage = this.current;
	// Ask user if this is really the intended action:
	var r=confirm("Er du sikker på at du vil slette dette elementet?");
	// If "yes", delete the element:
	if (r==true) {
		$.ajax({
			url: 'includes/functions/deleteElement.php',
			type: 'post',
			data: { id: id },
			success: function (data) {
				alert(data.message);
				if(data.ok) {
					page.getPage(currentPage);
				}
			}
		});
	}
	else {	// If not cancel the operation:
		return;
	}
}

/**
 * Gets the number of carousels already in the database
 *
 */
Page.prototype.getNumCarousels = function() {
	var res = "";
	$.ajax({
		url: "includes/functions/getNumCarousels.php",
		async: false,					// To be able to return info
		success: function (data){
			res = data.respond;
		}
	});
	return parseInt(res);
}

/**
 * Initiates the creation of a new image carousel
 *
 */
Page.prototype.newCarousel = function() {
	$.ajax({
		url: 'newCarousel.html',
		success: function (data) {
			$('#newElementContent').html (data);
		}
	});
	$('#newElement').modal('show');  // Display the New Element dialog
}

/**
 * Stores a new carousel element in the database
 *
 * @param form Content of HTML-form (newCarousel.html)
 */
Page.prototype.storeNewCarousel = function(form) {
	var num = this.getNumCarousels()+1;   // Get the number of exsisting carousels
	// Make the html-content:
	var content = '<div id="carousel_'+num+'" class="carousel slide" data-ride="carousel"><ol class="carousel-indicators">';
	content += '<li data-target="#carousel'+num+'" data-slide-to="0" class="active"></li>';
	for(i=1; i<form.ant.value; i++) {
		content += '<li data-target="#carousel'+num+'" data-slide-to="'+i+'"></li>';
	}
	content += '</ol><div class="carousel-inner">';
	for(i=1; i<=form.ant.value; i++) {
		sel = '#img_'+i;
		img = $(sel).val();
		if(i==1) {
			content += '<div class="item active"><img src="'+img+'" alt="Karusellbilde_'+i+'"></div>';
		}
		else {
			content += '<div class="item"><img src="'+img+'" alt="Karusellbilde_'+i+'"></div>';
		}
	}
	content += '</div><a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>';
	content += '<a class="right carousel-control" href="#carousel-example-generic" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a></div>';
	// Insert into database:
	$.ajax({
		url: 'includes/functions/storeNewElement.php',
		type: 'post',
		data: {carousel: true, content: content, pageId: this.current, index: form.index.value},
		success: function (data) {
			if (data.ok) {
				alert (data.message);
				page.getPage(page.current);			// "Reload" the page (this.current fungerer ikke)
				$('#newElement').modal('hide');  	// Hide the New Element dialog
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();
				$('#newElementContent').empty();  	// Empty the modal
			} else
				alert (data.message);
		}
	});
}

/**
 * Initilises editing of a carousel
 *
 * @param id int the id of the Carousel på edit
 */
Page.prototype.editCarousel = function (id) {
  $('#newElementContent').load('newCarousel.html');	// Get the form-html
  var currentPage = this.current;
	$.ajax ({
		url: 'includes/functions/getElement.php',  // Use this script to get the exsisting element
		type: 'post',
		data: { id: id },
		success: function (data) {		            // When data is returned
			if(data.message) {						// If something is wrong
				alert (data.message);
			}
			else {									// All is ok, fill in page data in form:
				$('h4[class="modal-title"]').text('Rediger karusell');
				var subject = data.elementText;
				// Get the URL's fron the content-string:
				regexp = /img\ssrc..(.+).alt/gi, // g for global match
				match = regexp.exec(subject),
				result = [];
				while(match != null){
					result.push(match[1]); // the second value is matched group
					match = regexp.exec(subject);
				}
				var countImages = result.length;	// Get number of URL's
				$('#ant').val(countImages);
				for( i=0; i<countImages; i++) {
					var num = i+1;
					$('#images').append('<label>Url: </label><input type="text" id="img_'+num+'" name="img_'+num+'" size="80" /><br/>');
					var sel = '#img_'+num;
					$(sel).val(result[i]);
				}
				// Insert input for moving of the element to another page:
				$('<label for="page">Flytt til annen side:</label><div class="form-group"><select id="page" name="page" class="form-control" style="width: 200px"></select></div>').insertBefore($('div[class="modal-footer"]'));
				// Get and append the options of other pages:
				$.ajax ({
					url: 'includes/functions/getMenuPages.php',  // Use this script to get the exsisting pages
					type: 'post',
					data: { forUser: true },
					success: function (data) {		            // When data is returned
						$('select[id="page"]').append ('<option value="0" selected>-- Ikke flytt siden --</option>');
						for (var i=0; i<data.length; i++) {		// Loop through all returned data and append each element to the page
							if(data[i].pageId != currentPage) {
								$('select[id="page"]').append ('<option value="'+data[i].pageId+'">'+data[i].pageName+'</option>');
							}
						}
					}
				});
				if(data.elementIndex < 999) {
					$('#newElementForm input[type="number"]').val(data.elementIndex);
				}
				if(data.showDate == 0) {
					$('#newElementForm input[type="checkbox"]').prop('checked', true);
				}
				$('#newElementForm input[type="button"]').attr("onClick", "javascript:storeEditedCarousel(this.form);");
				$('#newElementForm').append('<input type="hidden" name="elementid" value="'+data.elementId+'">');
				regexp = /div\sid..carousel.(\d+).\sclass/gi, // g for global match
				match = regexp.exec(subject);
				console.log(subject);
				$('#newElementForm').append('<input type="hidden" name="numberOfCarousels" value="'+match[1]+'">');
				$('#newElement').modal('show');  	// Show the dialog
			}
		}	
	});
}

/**
 * Stores the edited Carousel
 * For some reason this refuses to work as a class function...
 *
 * @param form Content of HTML-form (newCarousel.html, edit version)
 */
function storeEditedCarousel(form) {
	var num = form.numberOfCarousels.value;   // Get the number of exsisting carousels
	// Make the html-content:
	var content = '<div id="carousel_'+num+'" class="carousel slide" data-ride="carousel"><ol class="carousel-indicators">';
	content += '<li data-target="#carousel_'+num+'" data-slide-to="0" class="active"></li>';
	console.log($('#ant').val());
	for(i=1; i<form.ant.value; i++) {
		content += '<li data-target="#carousel'+num+'" data-slide-to="'+i+'"></li>';
	}
	content += '</ol><div class="carousel-inner">';
	for(i=1; i<=form.ant.value; i++) {
		sel = '#img_'+i;
		img = $(sel).val();
		if(i==1) {
			content += '<div class="item active"><img src="'+img+'" alt="Karusellbilde_'+i+'"></div>';
		}
		else {
			content += '<div class="item"><img src="'+img+'" alt="Karusellbilde_'+i+'"></div>';
		}
	}
	content += '</div><a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a>';
	content += '<a class="right carousel-control" href="#carousel-example-generic" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a></div>';
	console.log(content);
	// Insert into database:
	$.ajax({
		url: 'includes/functions/storeEditedElement.php',
		type: 'post',
		data: {carousel: true, id: form.elementid.value, content: content, index: form.index.value, page: form.page.value},
		success: function (data) {
			if (data.ok) {
				alert (data.message);
				page.getPage(data.id);			// "Reload" the page (this.current fungerer ikke)
				$('#newElement').modal('hide');  	// Hide the New Element dialog
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();
				$('#newElementContent').empty();  	// Empty the modal
			}
			else {
				alert (data.message);
			}
		}
	});
}
